<template>
  <div class="spatialDialogContainer" v-if="isSpatialDialogShow" v-drag>
    <div class="spatialDialogTitle drag-handle">
      <div class="title-left">
        <div class="bar"></div>
        <div class="title-text">空间查询统计</div>
      </div>
      <div class="title-right">
        <!-- <div  tabindex="0" class="icon">-</div> -->
        <div tabindex="0" class="icon" @click="closeDialog">×</div>
      </div>
    </div>
    <div class="spatialDialogContent">
      <div class="contentButton">
        <div
          class="menuButton"
          :class="{ active: isNormalShow }"
          @click="changeMenu('normal')"
        >
          区域查询
        </div>
        <div
          class="menuButton"
          :class="{ active: isAdvancedShow }"
          @click="changeMenu('advanced')"
        >
          区域设置
        </div>
      </div>
      <div
        v-if="isNormalShow"
        style="
          width: 100%;
          height: 30px;
          background-color: rgb(64, 112, 162);
          font-size: 16px;
          color: white;
          line-height: 30px;
        "
      >
        统计条件设定
      </div>
      <div v-if="isNormalShow" style="display: flex; justify-content: center">
        <div class="conditionContent" style="width: 100%; max-height: 10rem">
          <div
            class="conditionContent-type"
            style="
              display: flex;
              margin: 0 auto;
              justify-content: center;
              margin-top: 5px;
            "
          >
            <div style="display: flex; width: 100%">
              <div
                style="
                  width: 105px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isAllAreaShow }"
                @click="changeArea('all')"
              >
                全部区域
              </div>
              <div
                style="
                  width: 105px;
                  height: 25px;
                  margin-left: -3px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isNowAreaShow }"
                @click="changeArea('now')"
              >
                当前区域
              </div>
              <div
                style="
                  width: 120px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isEnvShow }"
                @click="changeArea('env')"
              >
                自定义矩形
              </div>
              <div
                style="
                  width: 120px;
                  height: 25px;
                  line-height: 25px;
                  background-color: #fff;
                  color: black;
                  border-radius: 3px;
                  text-align: center;
                "
                class="menuArea"
                :class="{ active: isCoorShow }"
                @click="changeArea('coor')"
              >
                自定义多边形
              </div>
            </div>
          </div>
          <div
            class="conditionContent-area"
            style="width: 300px; display: flex; margin-top: 10px"
          >
            <div
              v-show="isNowAreaShow"
              class="label"
              style="width: 60px; font-weight: bold"
            >
              区域
            </div>
            <div v-show="isNowAreaShow">
              <select
                v-model="targetOption"
                @change="targetSelect"
                style="width: 240px"
              >
                <!-- <option value="allArea">全部</option> -->
                <option
                  :value="item.areaValue"
                  v-for="item in templateTableData"
                >
                  {{ item.areaName }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <div v-if="isNormalShow">
        <div></div>
      </div>
      <div
        v-if="isNormalShow"
        style="
          width: 100%;
          height: 30px;
          background-color: rgb(64, 112, 162);
          font-size: 16px;
          color: white;
          line-height: 30px;
        "
      >
        统计结果
      </div>
      <div
        v-loading="isLoading"
        element-loading-text="正在加载数据中..."
        v-if="isNormalShow"
        style="width: 100%; margin-top: 10px"
      >
        <el-table
          :data="tableData"
          border
          id="dataTable"
          height="250"
          style="width: 100%"
        >
          <el-table-column prop="cnname" label="类别"></el-table-column>
          <el-table-column
            prop="equipmentNum"
            label="总数量(个)/总长度(公里)"
          ></el-table-column>
        </el-table>
        <div class="tablePage" v-if="false">
          <el-pagination
            @current-change="handleCurrentChange"
            :page-sizes="[10, 20, 30, 40]"
            :current-page="pageinfoItem.currentPage"
            :total="pageinfoItem.totalItems"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </div>
      <div
        v-if="isNormalShow"
        class="bottom-button"
        style="display: flex; justify-content: flex-end"
      >
        <el-button size="mini" icon="el-icon-s-data" @click="openStatisicDialog"
          >统计</el-button
        >
        <el-button size="mini" icon="el-icon-folder-opened" @click="exportForm">
          导出
        </el-button>
      </div>
      <!-- 高级统计界面 -->

      <div
        v-if="isAdvancedShow"
        style="
          width: 463px;
          height: 30px;
          background-color: #4070a2;
          font-size: 16px;
          color: white;
          line-height: 30px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>区域统计模板</div>
      </div>
      <div
        v-if="isAdvancedShow"
        style="width: 460px; height: 260px; margin-top: 10px"
      >
        <el-table
          :data="templateTableData"
          border
          height="250"
          style="width: 100%"
        >
          <el-table-column prop="areaName" label="名称"></el-table-column>
          <el-table-column prop="areaRemark" label="备注"></el-table-column>
          <!-- <el-table-column prop="areaValue" label="区域坐标"></el-table-column> -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="handleDelete(scope.$index, scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        v-if="isAdvancedShow"
        class="bottom-button"
        style="margin-left: 215px"
      >
        <el-button
          size="mini"
          icon="el-icon-circle-plus-outline"
          @click="addArea"
        >
          新增
        </el-button>
      </div>
    </div>
    <div class="sureSearch"></div>
    <AddArea
      :dialogVisible="isAddAreaShow"
      :areaData="areaText"
      @update:dialogVisible="isAddAreaShow = $event"
      @updateTemplateData="updateTemplateData"
    ></AddArea>

    <el-dialog
      title="管网资产统计图表"
      :modal="false"
      :close-on-click-modal="true"
      :visible.sync="dialogStatisicVisible"
    >
      <EChartsVue :chart-data="chartData"></EChartsVue>
    </el-dialog>
  </div>
</template>

<script>
import Polygon from "ol/geom/Polygon";
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import dmgis from "@/api/dmgis";
import {
  getEquipStatistics,
  getQueryTemplate,
  deleteSpatialTemplate,
  getChineseByEnglish,
} from "@/api/EquipmentManagement.js";
import AddArea from "./SpatialAddArea.vue";
import EChartsVue from "../../UtilView/ECharts.vue";
export default {
  name: "equipSpatial",
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  components: {
    AddArea,
    EChartsVue,
  },
  data() {
    return {
      pageinfoItem: {
        totalItems: 0,
        currentPage: 1,
        pageSize: 10,
      },
      isLoading: false,
      layerFeatureGroup: [],
      isAddAreaShow: false,
      isNormalShow: true,
      isAdvancedShow: false,
      targetOption: "",
      map: null,
      resultDataTemp: [],
      isAllAreaShow: true,
      isNowAreaShow: false,
      isEnvShow: false,
      isCoorShow: false,
      dialogStatisicVisible: false,
      tableData: [],
      templateTableData: [],
      areaData: null,
      areaText: "",
      projectLayer: null,
      chartData: {
        xAxisData: [],
        seriesData: [],
      },
      querySpatialLayer: null,
      querySpatialAreaLayer: null,
    };
  },
  computed: {
    isSpatialDialogShow() {
      // 返回 prop 的值
      return this.dialogVisible;
    },
    getArea() {
      return this.$store.state.area;
    },
  },
  beforeDestroy() {
    if (this.map) {
      this.map.interaction.cancelYjDraw();
      this.map.map.removeLayer(this.querySpatialAreaLayer);
      this.map.map.removeLayer(this.querySpatialLayer);
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.map.map.un("dblclick", this.getFeatureByMultiArea);
    }
  },
  watch: {
    getArea(newVal) {
      // console.log("绘制完成1");
      this.areaData = newVal;
      this.areaText = JSON.stringify(this.areaData.getCoordinates()[0]);
      if (this.isEnvShow) {
        this.getFeatureByArea(this.areaData);
      } else if (this.isCoorShow) {
        this.getFeatureByMultiArea(this.areaData);
      }
    },
    tableData(newVal) {
      this.chartData.xAxisData = [];
      this.chartData.seriesData = [];
      newVal.forEach((item) => {
        this.chartData.xAxisData.push(item.cnname.replace(/\s+/g, ""));
        this.chartData.seriesData.push(item.equipmentNum || item.totalLength);
      });
    },
  },
  methods: {
    handleCurrentChange(page) {
      this.pageinfoItem.currentPage = page;
    },
    initMap() {
      setTimeout(() => {
        this.map = this.$store.getters.Map;
        if (this.map) {
        } else {
          console.error("地图实例未找到");
        }
        this.projectLayer = this.$store.getters.projectLayer;
        this.querySpatialLayer =
          this.map.layer.createVectorLayer("空间查询点图层");
        this.querySpatialAreaLayer =
          this.map.layer.createVectorLayer("空间查询面图层");
      }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },
    changeMenu(val) {
      if (val == "normal") {
        this.isNormalShow = true;
        this.isAdvancedShow = false;
      } else {
        this.isNormalShow = false;
        this.isAdvancedShow = true;
      }
    },
    changeArea(val) {
      this.map.interaction.cancelYjDraw();
      this.querySpatialLayer.getSource().clear();
      this.querySpatialAreaLayer.getSource().clear();
      this.map.map.un("dblclick", this.getFeatureByArea);
      this.map.map.un("dblclick", this.getFeatureByMultiArea);
      switch (val) {
        case "all":
          this.isAllAreaShow = true;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = false;
          getEquipStatistics().then((res) => {
            this.tableData = res.data.map((item) => {
              return {
                cnname: item.cnname.replace(/\s+/g, ""),
                equipmentNum: item.equipmentNum || item.totalLength,
              };
            });
            this.tableData.push({
              cnname: "管线总长",
              equipmentNum: res.totalLineLength,
            });
            this.chartData.xAxisData = [];
            this.chartData.seriesData = [];
            for (let i = 0; i < this.tableData.length; i++) {
              this.chartData.xAxisData.push(
                this.tableData[i].cnname.replace(/\s+/g, "")
              );
              this.chartData.seriesData.push(
                this.tableData[i].equipmentNum || this.tableData[i].totalLength
              );
            }
          });
          break;
        case "now":
          this.isAllAreaShow = false;
          this.isNowAreaShow = true;
          this.isEnvShow = false;
          this.isCoorShow = false;
          break;

        case "env":
          this.map.interaction.addNewAreaDraw("Rectangle", 1);
          this.addEnvArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = true;
          this.isCoorShow = false;
          break;
        case "coor":
          this.map.interaction.addNewAreaDraw("Polygon", 1);
          this.addCoorArea();
          this.isAllAreaShow = false;
          this.isNowAreaShow = false;
          this.isEnvShow = false;
          this.isCoorShow = true;
          break;
      }
    },
    closeDialog() {
      // 通过修改 prop 来关闭弹窗
      this.$emit("update:dialogVisible", false);
    },
    targetSelect() {
      this.querySpatialLayer.getSource().clear();
      this.querySpatialAreaLayer.getSource().clear();
      let areaDataSelect = JSON.parse(this.targetOption);
      let polygon = new Polygon([areaDataSelect]);
      this.map.map.getView().fit(polygon, {
        duration: 1000,
      });
      this.map.layer.addPolygonsToLayer(
        this.querySpatialAreaLayer,
        [areaDataSelect],
        {
          fill: "rgba(255, 255, 255, 0.2)",
          strokeColor: "#6db6d2",
          strokeWidth: 2,
        }
      );
      this.isLoading = true;
      //调用dmgis服务
      let resultData = [];
      let getFeatureParams = new dmgis.object.FeatureServiceParam(
        "TapWaterMap"
      );
      let SpatialQuery = new dmgis.object.SpatialQuery();
      let areaPos = "";
      areaDataSelect.forEach((item, index) => {
        let itemGroup = item.join(" ");
        if (index == areaDataSelect.length - 1) {
          areaPos += itemGroup;
        } else {
          areaPos += itemGroup + ";";
        }
      });
      SpatialQuery.strPos = areaPos;
      getFeatureParams.sql = SpatialQuery;
      let layersAttribute = this.$store.state.layersAttribute;
      if (layersAttribute.length == 0) {
        this.$message.warning("请先获取服务图层");
        this.isLoading = false;
        return;
      }
      let requestNum = 0;
      requestNum = this.$store.state.layersAttribute.length;
      async function getFeatureByAreaSon() {
        for (let item of layersAttribute) {
          getFeatureParams.strlayername = item;
          try {
            await this.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                if (res.objset) {
                  let dataObjectgroup = [];
                  res.objset.map((item) => {
                    let dataObject = {};
                    item.rec.forEach((data) => {
                      dataObject[data.fldname] = data.fldval;
                    });
                    dataObjectgroup.push(dataObject);
                  });
                  resultData.push({
                    layername: getFeatureParams.strlayername,
                    data: dataObjectgroup,
                  });
                }
                // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                //   function (feature) {
                //     if (feature.objset) {
                //       let dataObjectgroup = [];
                //       feature.objset.map((item) => {
                //         let dataObject = {};
                //         item.rec.forEach((data) => {
                //           dataObject[data.fldname] = data.fldval;
                //         });
                //         dataObjectgroup.push(dataObject);
                //       });
                //       resultData.push({
                //         layername: getFeatureParams.strlayername,
                //         data: dataObjectgroup,
                //       });
                //     }
                //   };
              });
          } catch (error) {
            console.error("获取图层数据请求出错:", error);
          } finally {
            requestNum--;
            if (requestNum == 0) {
              this.$message.success("数据获取成功");
              this.isLoading = false;
              let engGroup = [];
              let chnGroup = [];
              //英取汉
              this.resultDataTemp = resultData;
              resultData.forEach((item) => {
                //加点
                item.data.forEach((data) => {
                  this.map.marker.addMarker(
                    data.X,
                    data.Y,
                    this.querySpatialLayer,
                    {
                      scale: 1.5, //大小
                      radius: 5,
                      pBorderColor: "#000000",
                      pBorderWidth: 1,
                      pFillColor: "",
                    },
                    data
                  );
                });
                // let parts = item.layername.split("_");
                // let result = parts.slice(0, 2).join("_");
                // item.layername = result;
                engGroup.push(item.layername);
              });
              await getChineseByEnglish(engGroup).then((res) => {
                chnGroup = res.data;
              });
              this.isLoading = false;
              this.chartData.xAxisData = [];
              this.chartData.seriesData = [];
              this.tableData = resultData.map((item) => {
                let dataName = chnGroup[item.layername];
                this.chartData.xAxisData.push(dataName);
                this.chartData.seriesData.push(item.data.length);
                return {
                  cnname: dataName,
                  equipmentNum: item.data.length,
                };
              });
            }
          }
        }
      }
      getFeatureByAreaSon.call(this);
    },
    handleDelete(index, row) {
      // 这里编写删除行的逻辑
      // 例如，从 tableData 中移除该行
      deleteSpatialTemplate({ id: row.id }).then((res) => {
        if (res.code == 200) {
          this.$message({
            showClose: true,
            message: res.message,
            type: "success",
          });
          for (let i = 0; i < this.templateTableData.length; i++) {
            if (this.templateTableData[i].id == row.id) {
              this.templateTableData.splice(i, 1);
            }
          }
        }
      });
    },
    // 新增区域按钮点击事件
    addArea() {
      this.map.interaction.addNewAreaDraw("Polygon", 1);
      this.map.map.on("dblclick", (event) => {
        // 你的处理逻辑
        this.isAddAreaShow = true;
        // 可以在这里执行你想要进行的操作，比如完成绘制等
      });
    },
    //自定义矩形区域点击按钮
    addEnvArea() {
      this.areaData = null;
      this.areaText = "";
      // this.map.map.on("dblclick", this.getFeatureByArea);
    },
    getFeatureByArea() {
      this.map.map.un("dblclick", this.getFeatureByArea);
      if (this.areaData) {
        this.isLoading = true;
        //调用dmgis服务
        let resultData = [];
        let areaRect = this.areaData.getCoordinates()[0];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let rect = new dmgis.object.Envelope(); //矩形范围
        rect.minx = areaRect[0][0];
        rect.miny = areaRect[0][1];
        rect.maxx = areaRect[2][0];
        rect.maxy = areaRect[2][1];
        SpatialQuery.env = rect; //矩形
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }

        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;
        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                this.resultDataTemp = resultData;
                //去下划线&&加点
                resultData.forEach((item) => {
                  //加点
                  item.data.forEach((data) => {
                    this.map.marker.addMarker(
                      data.X,
                      data.Y,
                      this.querySpatialLayer,
                      {
                        scale: 1.5, //大小
                        radius: 5,
                        pBorderColor: "#000000",
                        pBorderWidth: 1,
                        pFillColor: "",
                      },
                      data
                    );
                  });
                  engGroup.push(item.layername);
                });

                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.chartData.xAxisData = [];
                this.chartData.seriesData = [];
                let totalLength = 0;

                this.tableData = resultData.map((item) => {
                  let dataName = chnGroup[item.layername];
                  this.chartData.xAxisData.push(dataName);
                  this.chartData.seriesData.push(item.data.length);
                  if (item.layername.includes("pipeline")) {
                    let lens = 0;
                    item.data.forEach((item) => {
                      lens += Number(item.len);
                    });
                    totalLength += lens;
                    return {
                      cnname: dataName,
                      equipmentNum: (lens / 1000).toFixed(5),
                    };
                  } else {
                    return {
                      cnname: dataName,
                      equipmentNum: item.data.length,
                    };
                  }
                });
                this.tableData.push({
                  cnname: "管线总长",
                  equipmentNum: (totalLength / 1000).toFixed(5),
                });
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
      // this.map.interaction.cancelYjDraw();
      this.addEnvArea();
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: "矩形空间查询",
      //   message: h("p", null, [h("span", null, "是否查询该区域? ")]),
      //   showCancelButton: true,
      //   distinguishCancelAndClose: true,
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      // })
      //   .then((action) => {})
      //   .catch(() => {});
    },
    // 新增自定义多边形按钮点击事件
    addCoorArea() {
      this.areaData = null;
      this.areaText = "";
      // this.map.map.on("dblclick", this.getFeatureByMultiArea);
    },
    getFeatureByMultiArea() {
      // this.map.map.un("dblclick", this.getFeatureByMultiArea);
      if (this.areaData) {
        this.isLoading = true;
        //调用dmgis服务
        let resultData = [];
        let getFeatureParams = new dmgis.object.FeatureServiceParam(
          "TapWaterMap"
        );
        let SpatialQuery = new dmgis.object.SpatialQuery();
        let areaPos = "";
        this.areaData.getCoordinates()[0].forEach((item, index) => {
          let itemGroup = item.join(" ");
          if (index == this.areaData.getCoordinates()[0].length - 1) {
            areaPos += itemGroup;
          } else {
            areaPos += itemGroup + ";";
          }
        });
        SpatialQuery.strPos = areaPos;
        getFeatureParams.sql = SpatialQuery;
        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          this.isLoading = false;
          return;
        }
        let requestNum = 0;
        requestNum = this.$store.state.layersAttribute.length;

        async function getFeatureByAreaSon() {
          for (let item of layersAttribute) {
            getFeatureParams.strlayername = item;
            try {
              await this.projectLayer
                .SendFeatureMapService(getFeatureParams)
                .then((res) => {
                  if (res.objset) {
                    let dataObjectgroup = [];
                    res.objset.map((item) => {
                      let dataObject = {};
                      item.rec.forEach((data) => {
                        dataObject[data.fldname] = data.fldval;
                      });
                      dataObjectgroup.push(dataObject);
                    });
                    resultData.push({
                      layername: getFeatureParams.strlayername,
                      data: dataObjectgroup,
                    });
                  }
                  // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                  //   function (feature) {
                  //     if (feature.objset) {
                  //       let dataObjectgroup = [];
                  //       feature.objset.map((item) => {
                  //         let dataObject = {};
                  //         item.rec.forEach((data) => {
                  //           dataObject[data.fldname] = data.fldval;
                  //         });
                  //         dataObjectgroup.push(dataObject);
                  //       });
                  //       resultData.push({
                  //         layername: getFeatureParams.strlayername,
                  //         data: dataObjectgroup,
                  //       });
                  //     }
                  //   };
                });
            } catch (error) {
              console.error("获取图层特征时出错:", error);
            } finally {
              requestNum--;
              if (requestNum == 0) {
                this.$message.success("数据获取成功");
                this.isLoading = false;
                let engGroup = [];
                let chnGroup = [];
                //英取汉
                resultData.forEach((item) => {
                  item.data.forEach((data) => {
                    this.map.marker.addMarker(
                      data.X,
                      data.Y,
                      this.querySpatialLayer,
                      {
                        scale: 1.5, //大小
                        radius: 5,
                        pBorderColor: "#000000",
                        pBorderWidth: 1,
                        pFillColor: "",
                      },
                      data
                    );
                  });
                  // let parts = item.layername.split("_");
                  // let result = parts.slice(0, 2).join("_");
                  // item.layername = result;
                  engGroup.push(item.layername);
                });
                await getChineseByEnglish(engGroup).then((res) => {
                  chnGroup = res.data;
                });
                this.isLoading = false;
                this.chartData.xAxisData = [];
                this.chartData.seriesData = [];
                let totalLength = 0;

                this.tableData = resultData.map((item) => {
                  let dataName = chnGroup[item.layername];
                  this.chartData.xAxisData.push(dataName);
                  this.chartData.seriesData.push(item.data.length);
                  if (item.layername.includes("pipeline")) {
                    let lens = 0;
                    item.data.forEach((item) => {
                      lens += Number(item.len);
                    });
                    totalLength += lens;
                    return {
                      cnname: dataName,
                      equipmentNum: (lens / 1000).toFixed(5),
                    };
                  } else {
                    return {
                      cnname: dataName,
                      equipmentNum: item.data.length,
                    };
                  }
                });
                this.tableData.push({
                  cnname: "管线总长",
                  equipmentNum: (totalLength / 1000).toFixed(5),
                });
              }
            }
          }
        }
        getFeatureByAreaSon.call(this);
      }
      // this.map.interaction.cancelYjDraw();
      this.addCoorArea();
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: "多边形空间查询",
      //   message: h("p", null, [h("span", null, "是否查询该区域? ")]),
      //   showCancelButton: true,
      //   distinguishCancelAndClose: true,
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      // })
      //   .then((action) => {
      //     if (action == "confirm") {
      //     }
      //   })
      //   .catch(() => {});
    },
    openStatisicDialog() {
      this.dialogStatisicVisible = true;
    },
    async exportForm() {
      if (this.resultDataTemp.length === 0) {
        this.$message.warning("暂无可导出的数据!");
        return;
      }
      let wb = XLSX.utils.book_new();
      console.log(this.resultDataTemp, "this.resultDataTemp");

      for (const item of this.resultDataTemp) {
        let arrayTemp = [];
        let keyGroup = [];
        let arrayGroup = [];
        keyGroup = Object.keys(item.data[0]);
        await getChineseByEnglish(keyGroup).then((res) => {
          for (let key in res.data) {
            if (res.data.hasOwnProperty(key)) {
              arrayGroup.push(res.data[key]);
            }
          }
        });
        arrayTemp.push(arrayGroup);
        item.data.forEach(async (data, index) => {
          let arrayGroup = [];
          for (let key in data) {
            arrayGroup.push(data[key]);
          }
          arrayTemp.push(arrayGroup);
        });
        await getChineseByEnglish([item.layername]).then((res) => {
          let ws = XLSX.utils.aoa_to_sheet(arrayTemp);
          XLSX.utils.book_append_sheet(wb, ws, res.data[item.layername]);
        });
      }

      XLSX.writeFile(wb, "空间查询统计表.xlsx");
    },
    updateTemplateData() {
      this.templateTableData = [];
      getQueryTemplate().then((res) => {
        this.templateTableData = res.data;
      });
    },
  },

  mounted() {
    this.initMap();
    getEquipStatistics().then((res) => {
      this.tableData = res.data.map((item) => {
        return {
          cnname: item.cnname.replace(/\s+/g, ""),
          equipmentNum: item.equipmentNum || item.totalLength,
        };
      });
      this.tableData.push({
        cnname: "管线总长",
        equipmentNum: res.totalLineLength,
      });
      for (let i = 0; i < this.tableData.length; i++) {
        this.chartData.xAxisData.push(
          this.tableData[i].cnname.replace(/\s+/g, "")
        );
        this.chartData.seriesData.push(
          this.tableData[i].equipmentNum || this.tableData[i].totalLength
        );
      }
    });
    getQueryTemplate().then((res) => {
      this.templateTableData = res.data;
    });
    // let names = [
    //   "clampcollar_info",
    //   "threadedvalve_info",
    //   "unconfirmed_pipelines_center",
    // ];

    // getChineseByEnglish(names).then((res) => {});
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox {
  color: white;
}
.spatialDialogContainer {
  width: 25vw;
  color: white;
  position: absolute;
  top: 5vh;
  right: -19vw;
  height: 46vh;
  z-index: 2;
  .spatialDialogTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    font-size: 1rem;
    background-color: #285383;
    .title-left,
    .title-right {
      display: flex;
      align-items: center;
    }
    .bar {
      width: 5px; /* 小竖条的宽度 */
      height: 20px; /* 小竖条的高度 */
      background-color: white; /* 小竖条的颜色 */
      margin-right: 10px; /* 小竖条和文字之间的间距 */
    }
    .icon {
      width: 20px; /* 小方框的宽度 */
      height: 20px; /* 小方框的高度 */
      // border: 1px solid #4998f2; /* 小方框的边框 */
      margin-left: 5px; /* 小方框之间的间距 */
    }
    .icon:hover {
      color: #4998f2;
    }
    .icon:focus {
      color: #4998f2;
    }
  }
  .spatialDialogContent {
    padding: 10px;
    display: flex;
    flex-direction: column;
    background-color: #285383;
    font-size: 0.8rem;
    .contentButton {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px; /* 与下半部分内容的间距 */
      .menuButton {
        width: 50%;
        text-align: center;
        cursor: pointer;
      }
      .menuButton.active {
        // color: rgb(8, 46, 82);
        border-bottom: 2px solid white;
      }
    }
    .menuArea {
      cursor: pointer;
      margin: 0 2px !important;
    }
    .menuArea.active {
      background-color: #c4c6c8 !important;
    }
    .contentBox {
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      .formRow {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .search_input {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          input {
            width: 80%;
          }
        }
      }
      .label {
        width: 100px;
        margin-right: 10px;
      }

      select,
      textarea,
      button {
        width: 100%;
        color: white !important;
        background-color: #4070a2;
        border: none; /* 去除边框 */
        outline: none; /* 去除焦点时的轮廓线 */
        font-size: 0.8rem;
        height: 1.5rem;
      }

      button {
        margin-right: 10px; /* 按钮之间的间距 */
      }
      button:hover {
        background-color: #4998f2;
      }
      button:focus {
        background-color: #4998f2;
      }
      textarea {
        height: 5rem;
      }

      /* 最后一行的按钮不需要 label，可以单独设置样式 */
      .formRow:last-child {
        justify-content: flex-end;
      }

      .formRow:last-child .button {
        margin-left: 10px; /* 按钮之间的间距，而不是右边距 */
      }
    }
  }
}
.tablePage {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
  ::v-deep .el-pagination {
    button {
      color: #fff;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }
    .el-pagination__jump {
      color: #fff;
      background: transparent;
    }
    .el-input__inner {
      background: transparent;
      color: #fff;
    }
  }
  ::v-deep .el-pagination__total {
    color: #fff;
  }
  ::v-deep .el-pager {
    color: #fff;
    .number {
      margin: 0 0.3vw;
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
    }

    .btn-quickprev {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
    .btn-quicknext {
      background: transparent;
      border: 1px solid #ccc !important;
      border-radius: 5px;
      color: #fff;
    }
  }
}
</style>
